package com.woniu.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.woniu.entity.Question;
import com.woniu.entity.QuestionFeedback;
import com.woniu.entity.dto.ExamContent;
import com.woniu.entity.dto.ExamResult;
import com.woniu.entity.dto.ExamSubmission;
import com.woniu.service.ChatService;
import com.woniu.utils.ResultObj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 饶志
 * @version 1.0
 * @since 2025-06-11  14:43
 */
@RestController
@RequestMapping("api/ai")
@CrossOrigin
public class AIChatController {

    private static final Logger logger = LoggerFactory.getLogger(AIChatController.class);

    private final ChatService chatService;


    @Autowired
    public AIChatController(ChatService chatService) {
        this.chatService = chatService;
    }

    @RequestMapping("/chat")
    public String chat(@RequestParam("sessionId") String sessionId, @RequestParam("message") String message) {
        return chatService.processQuery(sessionId, message);
    }

    @RequestMapping(value = "/chatStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> chatStream(@RequestParam("sessionId") String sessionId, @RequestParam("message") String message,@RequestHeader(value = "Authorization", required = false) String token) {
        logger.info("sessionId: {}, message: {}", sessionId, message);
        // 手动检查token
        if (token == null || !token.startsWith("Bearer ")) {
            return Flux.error(new RuntimeException("请先登录系统"));
        }
        if (message == null || message.isEmpty()) {
            return Flux.error(new IllegalArgumentException("Message cannot be null or empty"));
        }
        return chatService.processQueryStream(sessionId, message);
    }



    @PostMapping("/generateExam")
    public ResultObj<ExamContent> generateExam(
            @RequestBody Map<String, Object> request
//            @RequestHeader(value = "Authorization", required = false) String token
    ) {

        // 验证token有效性
//        if (token == null) {
//            return ResultObj.error(401, "请提供有效Token");
//        }

        String content = request.get("content").toString();
        int count = 10; // 固定生成10道选择题

        try {
            ExamContent examContent = chatService.generateExamContent(content, count);
            return ResultObj.ok(examContent);
        } catch (Exception e) {
            logger.error("生成题目失败: {}", e.getMessage(), e);
            return ResultObj.error(500, "生成题目失败，请稍后再试");
        }
    }

    @PostMapping("/gradeExam")
    public ResultObj<ExamResult> gradeExam(@RequestBody ExamSubmission examSubmission) {
        try {
            ExamResult result = chatService.gradeExam(examSubmission);
            return ResultObj.ok(result);
        } catch (Exception e) {
            logger.error("评分失败: {}", e.getMessage(), e);
            return ResultObj.error(500, "评分失败，请稍后再试");
        }
    }

    private List<Question> parseExamContent(String content) {
        List<Question> questions = new ArrayList<>();
        String[] blocks = content.split("(?=### 选择题\\d+|\\d+\\.\\s*选择题)");

        for (String block : blocks) {
            if (block.trim().isEmpty()) continue;

            Question question = new Question();
            question.setType("choice"); // 强制设为选择题

            // 解析题号和标题
            String[] lines = block.split("\n");
            String firstLine = lines[0].trim();

            // 提取题目内容
            StringBuilder contentBuilder = new StringBuilder();
            boolean isOptions = false;

            for (int i = 0; i < lines.length; i++) {
                String line = lines[i].trim();

                if (line.startsWith("选项:")) {
                    isOptions = true;
                    question.setOptions(new ArrayList<>());
                    continue;
                }

                if (line.startsWith("答案:")) {
                    question.setAnswer(line.substring(3).trim());
                    isOptions = false;
                    continue;
                }

                if (line.startsWith("解析:")) {
                    question.setExplanation(line.substring(3).trim());
                    continue;
                }

                if (isOptions && line.matches("[A-D]\\.\\s*.+")) {
                    question.getOptions().add(line.substring(2).trim());
                    continue;
                }

                // 构建题目内容
                if (!line.isEmpty()) {
                    contentBuilder.append(line).append("\n");
                }
            }

            question.setContent(contentBuilder.toString().trim());
            question.setScore(10); // 每题10分
            questions.add(question);
        }

        return questions;
    }

    private String determineQuestionType(String content) {
        if (content.contains("判断题")) return "judge";
        if (content.contains("填空题")) return "fill";
        if (content.contains("编程题")) return "program";
        return "choice";
    }


}
